package sample.elasticjob.helloworld;

import org.apache.shardingsphere.elasticjob.api.JobConfiguration;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.lite.api.bootstrap.impl.ScheduleJobBootstrap;
import org.apache.shardingsphere.elasticjob.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperConfiguration;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperRegistryCenter;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;

/**
 * Created on 2020/8/11
 */
public class HelloWorldSample {

	public static void main(String[] args) {
		ScheduleJobBootstrap scheduleJobBootstrap = new ScheduleJobBootstrap(createRegistryCenter(), new MyJob(), createJobConfiguration());
		scheduleJobBootstrap.schedule();
	}

	private static JobConfiguration createJobConfiguration() {
		JobConfiguration jobConfig = JobConfiguration.newBuilder("MyJob", 3)
				.cron("0/5 * * * * ?")
				.build();
		return jobConfig;
	}

	private static CoordinatorRegistryCenter createRegistryCenter() {
		CoordinatorRegistryCenter regCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration("localhost:2181", "my-job"));
		regCenter.init();
		return regCenter;
	}

	public static class MyJob implements SimpleJob {

		@Override
		public void execute(ShardingContext context) {
			switch (context.getShardingItem()) {
			case 0:
				// do something by sharding item 0
				System.out.println("shardingItem 0");
				break;
			case 1:
				// do something by sharding item 1
				System.out.println("shardingItem 1");
				break;
			case 2:
				// do something by sharding item 2
				System.out.println("shardingItem 2");
				break;
			// case n: ...
			}
		}
	}
}
